-- 接收参数：商品ID、用户ID
local goodsId = KEYS[1]
local userId = KEYS[2]

-- 构造Redis中的key
local stockKey = "seckill:goods:" .. goodsId .. ":stock"
local userSetKey = "seckill:goods:" .. goodsId .. ":success_users"

-- 检查用户是否已经抢购成功（防重）
if redis.call('SISMEMBER', userSetKey, userId) == 1 then
    return 2 -- 重复抢购
end

-- 获取当前库存并尝试减少
local currentStock = redis.call('GET', stockKey)
redis.log(redis.LOG_WARNING, "Current stock value: " .. tostring(currentStock))
print("Current stock: " .. tostring(currentStock))
-- 确保存在且大于0才允许购买
if not currentStock or tonumber(currentStock) == nil or tonumber(currentStock) <= 0 then
    return 0 -- 库存不足
end

-- 原子化地减少库存并添加用户至已购列表
redis.call('DECR', stockKey)
redis.call('SADD', userSetKey, userId)

return 1 -- 抢购成功
